// 蓝牙协议处理模块
export class BLEProtocol {
  static SYNC_HEADER = 0xA5;

  // 构造指令帧
  static buildCommand(cmd: number, data: number[] = []): ArrayBuffer {
    const length = 4 + data.length; // 同步头+长度+命令+数据
    const buffer = new ArrayBuffer(length ); // 包含校验码
    const view = new DataView(buffer);
    
    let checksum = 0;
    let offset = 0;
    
    // 同步头
    view.setUint8(offset++, this.SYNC_HEADER);
    checksum += this.SYNC_HEADER;
    
    // 长度
    view.setUint8(offset++, length);
    checksum += length;
    
    // 命令
    view.setUint8(offset++, cmd);
    checksum += cmd;
    
    // 数据
    data.forEach(value => {
      view.setUint8(offset++, value);
      checksum += value;
    });
    
    // 校验码（无进位累加和）
    view.setUint8(offset, checksum & 0xFF);
    
    return buffer;
  }

  // 构造密码指令
  static buildPasswordCommand(password: string): ArrayBuffer {
    const paddedPwd = password.padEnd(6, '0').slice(0,6);
    const bytes = [...paddedPwd].map(c => parseInt(c));
    return this.buildCommand(0x01, bytes);
  }

  // 解析响应数据
  static parseResponse(buffer: ArrayBuffer): {
    cmd: number,
    status: number,
    data: number[]
  } {
    if (!buffer || buffer.byteLength < 4) {
      throw new Error('无效的响应数据长度');
    }

    const view = new DataView(buffer);
    const syncHeader = view.getUint8(0);
    
    if (syncHeader !== 0x5A) {
      throw new Error('无效的响应头');
    }

    const length = view.getUint8(1);
    if (length < 4 || length > buffer.byteLength) {
      throw new Error('无效的响应长度字段');
    }

    const cmd = view.getUint8(2);
    const data = [];
    
    // 确保不会越界访问
    const dataEnd = Math.min(length, buffer.byteLength);
    for (let i = 3; i < dataEnd - 1; i++) {
      data.push(view.getUint8(i));
    }

    // 校验码验证
    const expectedChecksum = Array.from(new Uint8Array(buffer))
      .slice(0, length - 1)
      .reduce((sum, val) => sum + val, 0) & 0xFF;
    
    const actualChecksum = view.getUint8(length - 1);
    
    if (expectedChecksum !== actualChecksum) {
      throw new Error('校验码不匹配');
    }

    return {
      cmd,
      status: data.length > 0 ? data[0] : 0,
      data: data.length > 1 ? data.slice(1) : []
    };
  }

  // 解析行车参数
  static parseRidingParams(data: number[]) {
    return {
      battery: data[0],
      speed: (data[1] << 8 | data[2]) / 10,
      totalMileage: (data[3] << 8 | data[4]) / 10,
      currentMileage: (data[5] << 8 | data[6]) / 10,
      ridingTime: data[7] << 8 | data[8],
      status: {
        lock: (data[9] & 0x80) >> 7,
        unit: (data[9] & 0x40) >> 6,
        headlight: (data[9] & 0x20) >> 5,
        autoHeadlight: (data[9] & 0x10) >> 4,
        mode: (data[9] & 0x08) >> 3,
        cruise: (data[9] & 0x04) >> 2,
        gear: data[9] & 0x03
      },
      errors: data[10]
    };
  }
}